<script>
  import tree from '@/mixins/tree/index.js'
  import AjaxStore from '@/utils/store/proxyAjax'
  import store from './store'
  import { validateTelephone } from '@/utils/validate'
  // import { validateNumber, validateTelephone } from '@/utils/validate'
  import GroupTree from '@/components/DatagroupTree'

export default {
    name: 'group',
    mixins: [tree, store],
    components: { GroupTree },
    data() {
      // const validateOrderNo = (rule, value, callback) => {
      //   if (value && !validateNumber(value)) {
      //     callback(new Error('请输入整数'))
      //   } else {
      //     callback()
      //   }
      // }
      const validateTel = (rule, value, callback) => {
        if (!value || value && validateTelephone(value)) {
          callback()
        } else {
          callback(new Error('手机号格式不正确'))
        }
      }
      return {
        editGroupId: '',
        groupName: '',
        fullPath: '',
        cNodeStr: '',
        cNode: [],

        // tree
        tree: {
          width: "280",
          accordion: false,
          isShowHeader: true,
          treeMenuButtonList: this.treeMenuBtns,
          treeOperateButtonList: this.treeOperateBtns,
          showCheckbox: false,
          selectTree: {},
          nextNodeKey: 'node',
          idKey: 'groupId',
          search: {
            searchKey: 'nodeName'
          },
          title: '组织机构',
          getNextChildNode: this.getNextNode,
          delNode: this.delNode
        },

        pidKey: 'pid',
        idKey: 'groupId',
        labelKey: 'groupName',
        nodeCheckedKey: 'checked',
        nodeChildrenKey: 'children',
        nodeLeafKey: "leaf",
        nodeIdKey: 'id',
        nodeLabelKey: 'text',

        currentNode: null,
        panelType: '',

        addNodeInfoUrl: '/v1/sys/group/add',
        updateNodeInfoUrl: '/v1/sys/group/update',
        getNextNodeUrl: '/v1/sys/group/findNextChildNodeTree',
        delNodeUrl: '/v1/sys/group/deleteNode',
        getNodeInfoUrl: '/v1/sys/group/findById',
        store: new AjaxStore({
          url: '/v1/sys/group/query'
        }),

        formPanel: {
          add: {
            model: {
              "groupId": '',
              "districtId": '',
              "pid": '',
              "groupNo": '',
              "groupName": '',
              "fullName": '',
              "shortName": '',
              "fullPath": '',
              "orderNo": '',
              "address": '',
              "linkMan": '',
              "telephone": '',
              "postCode": '',
              "dataStatus": 1,
              "json": '',
              "version": '',
              "creator": '',
              "createdTime": '',
              "updator": '',
              "updatedTime": '',
              "remark": ''
            },
            fields: [
              { label: '上级机构', prop: 'pid', placeholder: '请选择上级机构', anchor: 24, xType: 'SelectTree.TREE', ref: 'addGroup', relatedFields: ['addGroupPath'],
                treeParams: {
                  get: {
                    url: '/v1/dataProvider/getGroupTreeList',
                    nextNodeKey: 'pid',
                    idKey: 'id'
                  }
                },
                valueToLabelParams: {
                  url: '/v1/dataProvider/getGroupName',
                  idKey: 'groupId'
                },
                on: {
                  'visible-change': val => val && this.$refs.addForm.$refs.addGroup.reload()
                }
              },
              { label: '机构编码', prop: 'groupNo', placeholder: '输入机构编码', anchor: 24 },
              { label: '机构名称', prop: 'groupName', placeholder: '输入机构名称', anchor: 24,
                on: {
                  input: (val) => {
                    this.groupName = val
                    if (!this.formPanel.add.model.pid) {
                      this.formPanel.add.model.fullPath = this.filterArray([this.groupName]).join('/')
                    } else {
                      const selectGroupLabel = this.$refs.addForm.$refs.addGroup.selectedLabel
                      this.formPanel.add.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, selectGroupLabel), this.groupName]).join('/')
                    }
                  }
                }
              },
              { label: '机构全称', prop: 'fullName', placeholder: '输入机构全称', anchor: 24 },
              { label: '机构简称', prop: 'shortName', placeholder: '输入机构简称', anchor: 24 },
              { label: '状态', prop: 'dataStatus', xType: 'switch', anchor: 24, "active-value": 1, "inactive-value": 0 },
              { label: '排序号', prop: 'orderNo', placeholder: '输入排序号', anchor: 24 },
              { label: '联系人', prop: 'linkMan', placeholder: '输入联系人', anchor: 24 },
              { label: '联系地址', prop: 'address', placeholder: '输入联系地址', anchor: 24 },
              { label: '联系电话', prop: 'telephone', placeholder: '输入联系电话', anchor: 24,
                on: {
                  input: (val) => {
                    this.telephone = val
                    this.$refs.addForm.validateField('telephone')
                  }
                }
              },
              { label: '备注', prop: 'remark', placeholder: '输入备注', anchor: 24, type: 'textarea' },
              { label: '全路径', prop: 'fullPath', anchor: 24, readonly: true, style: 'border: 0;', ref: 'addGroupPath',
                on: {
                  'el.form.update': (val, ctx, origin, form) => { // 值,当前组件,关联组件
                    if (form.model.pid) {
                      this.getNodeInfo({ groupId: form.model.pid }).then(({ success, data }) => {
                        if (success && data.fullPath) {
                          // 获取上级机构全路径
                          this.fullPath = data.fullPath
                          this.formPanel.add.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, origin.selectedLabel), form.model.groupName]).join('/')
                        }
                      })
                    } else {
                      form.model.fullPath = this.filterArray([form.model.groupName]).join('/')
                    }
                  }
                }
              }
            ],
            rules: {
              "groupNo": [{ required: true, message: '请输入机构编码', trigger: 'blur' }],
              "groupName": [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
              "dataStatus": [{ required: true, message: '请输入数据状态', trigger: 'blur' }],
              "telephone": [{ required: false, trigger: "blur", validator: validateTel }]
              // "orderNo": [{ validator: validateOrderNo, trigger: 'blur' }]
            },
            title: '新增组织机构',
            type: 'ADD',
            ref: 'addForm',
            submitBtnList: this.addBtns
          },
          edit: {
            model: {
              "groupId": '',
              "districtId": '',
              "pid": '',
              "groupNo": '',
              "groupName": '',
              "fullName": '',
              "shortName": '',
              "fullPath": '',
              "orderNo": '',
              "address": '',
              "linkMan": '',
              "telephone": '',
              "postCode": '',
              "dataStatus": 0,
              "json": '',
              "version": '',
              "creator": '',
              "createdTime": '',
              "updator": '',
              "updatedTime": '',
              "remark": ''
            },
            fields: [
              { label: '上级机构', prop: 'pid', placeholder: '请选择上级机构', anchor: 24, xType: 'SelectTree.TREE', ref: 'editGroup', relatedFields: ['editGroupPath'],
                on: {
                  'update': (val, vnode, form) => {
                    const selfId = this.editGroupId
                    const $tree = vnode.$refs.tree
                    const path = $tree.getNodePath(val) || []
                    for (let i = 0, len = path.length; i < len; i++) {
                      if (selfId === path[i]['id']) {
                        form.model.pid = ''
                        this.$message({
                          type: 'error',
                          message: '组织机构上级机构不能选择自身或自己的子节点！'
                        })
                        break
                      }
                    }
                  },
                  'visible-change': val => val && this.$refs.editForm.$refs.editGroup.reload()
                },
                treeParams: {
                  get: {
                    url: '/v1/dataProvider/getGroupTreeList',
                    nextNodeKey: 'pid',
                    idKey: 'id'
                  }
                },
                valueToLabelParams: {
                  url: '/v1/dataProvider/getGroupName',
                  idKey: 'groupId'
                }
              },
              { label: '机构编码', prop: 'groupNo', placeholder: '输入机构编码', anchor: 24 },
              { label: '机构名称', prop: 'groupName', placeholder: '输入机构名称', anchor: 24,
                on: {
                  input: (val) => {
                    this.groupName = val
                    if (!this.formPanel.edit.model.pid) {
                      this.formPanel.edit.model.fullPath = this.filterArray([this.groupName]).join('/')
                    } else {
                      const selectGroupLabel = this.$refs.editForm.$refs.editGroup.selectedLabel
                      this.formPanel.edit.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, selectGroupLabel), this.groupName]).join('/')
                    }
                  }
                }
              },
              { label: '机构全称', prop: 'fullName', placeholder: '输入机构全称', anchor: 24 },
              { label: '机构简称', prop: 'shortName', placeholder: '输入机构简称', anchor: 24 },
              { label: '状态', prop: 'dataStatus', xType: 'switch', anchor: 24, "active-value": 1, "inactive-value": 0 },
              { label: '排序号', prop: 'orderNo', placeholder: '输入排序号', anchor: 24 },
              { label: '联系人', prop: 'linkMan', placeholder: '输入联系人', anchor: 24 },
              { label: '联系地址', prop: 'address', placeholder: '输入联系地址', anchor: 24 },
              { label: '联系电话', prop: 'telephone', placeholder: '输入联系电话', anchor: 24,
                on: {
                  input: (val) => {
                    this.telephone = val
                    this.$refs.addForm.validateField('telephone')
                  }
                }
              },
              { label: '备注', prop: 'remark', placeholder: '输入备注', anchor: 24, type: 'textarea' },
              { label: '全路径', prop: 'fullPath', anchor: 24, readonly: true, style: 'border: 0;', ref: 'editGroupPath',
                on: {
                  'el.form.update': (val, ctx, origin, form) => { // 值,当前组件,关联组件
                    if (form.model.pid) {
                      this.getNodeInfo({ groupId: form.model.pid }).then(({ success, data }) => {
                        if (success && data.fullPath) {
                          // 获取上级机构全路径
                          this.fullPath = data.fullPath
                          this.formPanel.edit.model.fullPath = this.filterArray([this.getFrontStr(this.fullPath, origin.selectedLabel), form.model.groupName]).join('/')
                        }
                      })
                    } else {
                      form.model.fullPath = this.filterArray([form.model.groupName]).join('/')
                    }
                  }
                }
              }
            ],
            rules: {
              "groupNo": [{ required: true, message: '请输入机构编码', trigger: 'blur' }],
              "groupName": [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
              "dataStatus": [{ required: true, message: '请输入数据状态', trigger: 'blur' }],
              "telephone": [{ required: false, trigger: "blur", validator: validateTel }]
              // "orderNo": [{ validator: validateOrderNo, trigger: 'blur' }]
            },
            title: '编辑组织机构',
            type: 'EDIT',
            ref: 'editForm',
            submitBtnList: this.editBtns
          }
        }
      }
    },
    methods: {
      getFrontStr(str, reg) {
        return str.split(reg)[0] + reg
      },
      handleSelect(node) {
        if (node.data.text) {
          if (node.parent) {
            this.handleSelect(node.parent)
          }
          this.cNode.push(node.data.text)
        }
      },
      // eslint-disable-next-line
      renderTree(h) {
        return (
          <GroupTree
            ref="tree"
            tree={ this.tree }
            on-add-treeNode={ this.handleNodeAdd }
            on-check-treeNode={ this.handleNodeEdit }
            on-del-treeNode={ this.handleNodeDel}
            on-tree-empty={ this.handleTreeEmpty }
            on-tree-subSelect= { this.handleTreeSubSelect }
            on-tree-import= { this.handleTreeImport }
            node-str={this.cNodeStr}
          ></GroupTree>
        )
      }
    },
    beforeCreate() {
      // 根据页面路由找出有权限访问的 url 数组
      const urlArr = (this.$route.meta && this.$route.meta.children || []).map(item => item.url)

      // 根据权限 url 数组过滤出能够使用的 按钮数组
      this.addBtns = [
        { label: '保存', methods: 'handleFormAdd', url: '/v1/sys/group/add', icon: 'el-icon-circle-check-outline', type: 'primary', disabled: false }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.editBtns = [
        { label: '保存', methods: 'handleFormEdit', url: '/v1/sys/group/update', icon: 'el-icon-circle-check-outline', type: 'primary', disabled: false }
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.treeMenuBtns = [
        { label: '新增', methods: 'handleMenuAdd', url: '/v1/sys/group/add', icon: 'el-icon-circle-plus-outline', type: 'text', action: 'plus' },
        { label: '刷新', methods: 'refresh', url: '/v1/sys/group/findNextChildNodeTree', icon: 'el-icon-refresh', type: 'text' },
        { label: '展开', methods: 'expand', url: '/v1/sys/group/findNextChildNodeTree', icon: 'el-icon-rank', type: 'text' },
        { label: '折叠', methods: 'fold', url: '', icon: 'el-icon-arrow-up', type: 'text' }
        // { label: '同步', methods: 'handleSync', url: '/v1/sys/syn/synGroup', path: '/v1/sys/syn/synGroup?allPath=', icon: 'el-icon-sort', type: 'text' ,action: 'sync'}
      ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url)

      this.treeOperateBtns = (data) => {
        // 根据 systemType 帅选
        let btnList = []
        !data.systemType
          ? (btnList = [
            { type: 'text', url: '/v1/sys/group/add', icon: 'el-icon-plus', action: 'plus' },
            { type: 'text', url: '/v1/sys/group/deleteNode', icon: 'el-icon-delete', action: 'delete' }
          ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url))
          : (btnList = [
            { type: 'text', url: '/v1/sys/group/add', icon: 'el-icon-plus', action: 'plus' },
            { type: 'text', url: '/v1/sys/group/deleteNode', icon: 'el-icon-remove', action: 'delete' }
          ].filter(item => (item.url && urlArr.includes(item.url)) || !item.url))
        return btnList
      }
    }
  }
</script>

<style lang="scss">
.group {
  .right {
    .c-button-list {
      justify-content: flex-end;
    }
  }
}
</style>

